﻿using Minio;
using Minio.ApiEndpoints;
using Minio.DataModel.Args;
using Minio.Exceptions;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace MarkDownFileSplitter
{
    public class DifyFileUploader
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiKey;
        private readonly string _baseUrl;

        /// <summary>
        /// 初始化知识库更新工具
        /// </summary>
        /// <param name="apiKey">Dify API密钥</param>
        /// <param name="baseUrl">Dify服务地址，如http://192.168.2.231</param>
        public DifyFileUploader(string apiKey, string baseUrl)
        {
            _apiKey = apiKey;
            _baseUrl = baseUrl.TrimEnd('/');
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
        }

        /// <summary>
        /// 上传文件到指定知识库
        /// </summary>
        /// <param name="datasetId">知识库ID</param>
        /// <param name="filePath">本地文件路径</param>
        /// <param name="indexingTechnique">索引技术（默认high_quality）</param>
        public async Task<JObject> UploadDocument(string datasetId, string filePath, string indexingTechnique = "high_quality")
        {
            // 构建多部分表单内容 
            using var content = new MultipartFormDataContent();

            // 添加JSON配置参数
            var processRule = new JObject
            {
                ["rules"] = new JObject
                {
                    ["pre_processing_rules"] = new JArray
                {
                    new JObject { ["id"] = "remove_extra_spaces", ["enabled"] = false },
                    new JObject { ["id"] = "remove_urls_emails", ["enabled"] = false }
                },
                    ["segmentation"] = new JObject
                    {
                        ["separator"] = "\\n\\n",
                        ["max_tokens"] = 3800
                    }
                },
                ["mode"] = "custom"
            };

            var dataParams = new JObject
            {
                ["indexing_technique"] = indexingTechnique,
                ["process_rule"] = processRule
            };

            var dataContent = new StringContent(
                dataParams.ToString(),
                Encoding.UTF8,
                "text/plain"); // 必须指定ContentType 
            content.Add(dataContent, "data");

            // 添加文件内容
            var fileStream = File.OpenRead(filePath);
            var streamContent = new StreamContent(fileStream);
            streamContent.Headers.ContentType =
                MediaTypeHeaderValue.Parse(GetMimeType(filePath));

            content.Add(
                content: streamContent,
                name: "file", // 字段名必须为file 
                fileName: Path.GetFileName(filePath));

            // 发送请求
            var response = await _httpClient.PostAsync(
                $"{_baseUrl}/v1/datasets/{datasetId}/document/create-by-file",
                content);

            response.EnsureSuccessStatusCode();
            return JObject.Parse(await response.Content.ReadAsStringAsync());
        }

        /// <summary>
        /// 查询文档分段
        /// </summary>
        /// <param name="datasetId">知识库ID</param>
        /// <param name="documentId">文档ID</param>
        /// <returns></returns>
        public async Task<JObject> QuerySegments(string datasetId, string documentId)
        {
            // 发送请求
            var response = await _httpClient.GetAsync($"{_baseUrl}/v1/datasets/{datasetId}/documents/{documentId}/segments");
            response.EnsureSuccessStatusCode();
            return JObject.Parse(await response.Content.ReadAsStringAsync());
        }

        public async Task<JObject> UpdateSegment(string datasetId, string documentId, string segmentId, string originContent, JArray keywords)
        {
            // 构建请求体
            var requestBody = new JObject
            {
                ["segment"] = new JObject
                {
                    ["content"] = originContent,
                    ["keywords"] = keywords,
                }
            };
            // 发送请求
            var response = await _httpClient.PostAsync($"{_baseUrl}/v1/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}", new StringContent(requestBody.ToString(), Encoding.UTF8, "application/json"));
            response.EnsureSuccessStatusCode();
            return JObject.Parse(await response.Content.ReadAsStringAsync());
        }

        public async Task<bool> GetIndexingStatus(string datasetId, string batch)
        {
            // 发送请求获取索引状态
            var response = await _httpClient.GetAsync($"{_baseUrl}/v1/datasets/{datasetId}/documents/{batch}/indexing-status");
            response.EnsureSuccessStatusCode();

            // 解析响应内容
            var result = JObject.Parse(await response.Content.ReadAsStringAsync());

            // 获取第一条数据的indexing_status
            var indexingStatus = result["data"]?[0]?["indexing_status"]?.ToString();

            // 判断索引状态是否为completed
            return indexingStatus == "completed";
        }

        /// <summary>
        /// 根据文件扩展名获取MIME类型
        /// </summary>
        private string GetMimeType(string filePath)
        {
            var extension = Path.GetExtension(filePath).ToLower();
            return extension switch
            {
                ".txt" => "text/plain",
                ".pdf" => "application/pdf",
                ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                ".csv" => "text/csv",
                ".pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                _ => "application/octet-stream"
            };
        }
    }
}